import type { CommandModule, Argv } from "yargs";
import { failHandler, getPkgInfo } from "@/common";
import type { ChildCmd } from "./handler";
import { handler } from "./handler";
import _curry from "lodash.curry";

const { version } = getPkgInfo();

const getCli = (cli: Argv, usage: string) => {
  return cli
    .strict()
    .recommendCommands()
    .usage(usage)
    .help("help")
    .version(version)
    .alias("v", "version")
    .alias("h", "help")
    .fail(_curry(failHandler)("CHILD_CMD"));
};

const builder = (cli: Argv, usage: string) => {
  return getCli(cli, usage) as unknown as Argv;
};

export const getCommand = ({
  command,
  describe,
}: {
  command: ChildCmd;
  describe: string;
}): CommandModule => {
  if (command === "add") {
    return {
      command: `${command} [name]`,
      describe,
      builder: (cli) => {
        cli.positional("name", {
          describe: "组件名称",
          type: "string",
        });
        return builder(cli, `Usage: $0 ${command} [name]`);
      },
      handler: _curry(handler)(command),
    };
  } else {
    return {
      command,
      describe,
      builder: (cli) => builder(cli, `Usage: $0 ${command}`),
      handler: _curry(handler)(command),
    };
  }
};
